package com.fujitsu.cn.fnst.controller;

import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fujitsu.cn.fnst.base.BaseController;
import com.fujitsu.cn.fnst.base.CommonParamter;
import com.fujitsu.cn.fnst.base.DateUtils;
import com.fujitsu.cn.fnst.base.LogUtils;
import com.fujitsu.cn.fnst.base.Param;
import com.fujitsu.cn.fnst.base.StringUtils;
import com.fujitsu.cn.fnst.base.ThirdVelocityEmailService;
import com.fujitsu.cn.fnst.convertor.DateConvertor;
import com.fujitsu.cn.fnst.entiy.Meeting;
import com.fujitsu.cn.fnst.entiy.MeetingBook;
import com.fujitsu.cn.fnst.entiy.MeetingUse;
import com.fujitsu.cn.fnst.entiy.User;
import com.fujitsu.cn.fnst.enums.BookState;
import com.fujitsu.cn.fnst.enums.UserRight;
import com.fujitsu.cn.fnst.exception.Resource404Exception;
import com.fujitsu.cn.fnst.service.MeetingBookService;
import com.fujitsu.cn.fnst.service.MeetingService;
import com.fujitsu.cn.fnst.service.MeetingUseService;
import com.fujitsu.cn.fnst.service.UserService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
public class IndexController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = LogUtils
			.getLogger(IndexController.class);

	@Resource
	private Producer captchaProducer;
	@Resource
	private UserService userService;
	@Resource
	private MeetingBookService meetingBookService;
	@Resource
	private MeetingUseService meetingUseService;
	@Resource
	private MeetingService meetingsService;
	@Resource
	private ThirdVelocityEmailService thirdVelocityEmailService;

	private static final int MAXAGE = 60 * 60 * 24 * 30;
	private static final List<String> adminLinks = new ArrayList<String>(5);
	static {
		adminLinks.add("books");
		adminLinks.add("logs");
		adminLinks.add("meetings");
		adminLinks.add("users");
		adminLinks.add("tops");
	}

	@RequestMapping(value = { "/login", "/" }, method = RequestMethod.GET)
	public String login(Model model, HttpSession session,
			HttpServletRequest request) {
		String cookieValue = null;
		if ((cookieValue = getCookieValue(request, "user")) != null
				// 用户删除cookie无法立即删除，在浏览器关闭时才删除
				&& getCookieMaxAge(request, "user") != 0
				&& getCookieMaxAge(request, "user") != -1 && !isLogin(session)) {
			User user = userService.findByWorkerId(cookieValue);
			if (user != null) {
				session.setAttribute(LOGIN, "true");
				session.setAttribute("user", user);
				cookieValue = getCookieValue(request, ADMIN);
				// 设置是否是管理员
				if (cookieValue != null) {
					session.setAttribute(ADMIN, cookieValue);
				}
				MDC.put("userId", user.getWorkerId());
				MDC.put("userType", "0");
				logger.info("用户工号" + user.getWorkerId() + ",姓名"
						+ user.getUserName() + "通过cookie上线了");
			}
		}
		if (!isLogin(session)) {
			model.addAttribute("error", "-1");
			return "login/login";
		}
		if (isAdmin(session)) {
			return redirect("/admin");
		}
		return redirect("/index");
	}

	@RequestMapping(value = { "/login" }, method = RequestMethod.POST)
	public String login(String user, String pwd, String isAdmin,
			String checkCode, String rememberme, HttpSession session,
			Model model, HttpServletRequest request,
			HttpServletResponse response) {
		if (user == null || user.trim().equals("")) {
			model.addAttribute("error", "请输入用户名!");
			return "login/login";
		}
		if (pwd == null || pwd.trim().equals("")) {
			model.addAttribute("error", "请输入密码!");
			return "login/login";
		}
		if (checkCode == null || checkCode.trim().equals("")) {
			model.addAttribute("error", "请输入验证码!");
			return "login/login";
		}
		String code = (String) session
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (!code.equals(checkCode)) {
			model.addAttribute("error", "验证码不正确!");
			return "login/login";
		}

		User user1 = userService.findUser(user);
		if (user1 == null) {
			model.addAttribute("error", "请输入正确的用户名!");
			return "login/login";
		}
		if (isAdmin.equals("true")) {
			if (user1.getIsAdmin() != CommonParamter.IS_ADMIN) {
				model.addAttribute("error", "请选择正确的权限!");
				return "login/login";
			}
		}
		if (!user1.getPwd().equals(StringUtils.encrypt(pwd))) {
			model.addAttribute("error", "请输入正确的密码!");
			return "login/login";
		}
		session.setAttribute(LOGIN, "true");
		session.setAttribute("user", user1);
		session.setAttribute(ADMIN, isAdmin);
		MDC.put("userId", user1.getWorkerId());
		MDC.put("userType", isAdmin(session) ? 0 : 1);
		logger.info("用户工号" + user1.getWorkerId() + ",姓名" + user1.getUserName()
				+ "上线了");
		if (rememberme != null && rememberme.equals("true")) {
			setCookie(request, response, "user", user, MAXAGE, true);
			setCookie(request, response, ADMIN, isAdmin, MAXAGE, true);
		}
		if (isAdmin(session)) {
			return redirect("/admin");
		}
		return redirect("/index");
	}

	@RequestMapping(value = { "/index", "/admin" })
	public String index(Model model, HttpSession session,
			HttpServletRequest request, HttpServletResponse response) {
		String cookieValue = null;
		if ((cookieValue = getCookieValue(request, "user")) != null
				&& isLogin(session) == false) {
			User user = userService.findByWorkerId(cookieValue);
			if (user != null) {
				session.setAttribute(LOGIN, "true");
				session.setAttribute("user", user);
				MDC.put("userId", user.getWorkerId());
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("用户工号" + user.getWorkerId() + ",姓名"
						+ user.getUserName() + "通过cookie上线了");
			}
		}
		if (!isLogin(session)) {
			if (isAdmin(session)) {
				return redirect("/admin");
			}
			return redirect("/login");
		}
		cookieValue = getCookieValue(request, PREFERENCE, true);
		if (cookieValue == null) {
			session.setAttribute(PREFERENCE, "time");
		} else {
			session.setAttribute(PREFERENCE, cookieValue);
		}
		if (isAdmin(session)) {
			return "admin/admin";
		}
		return "index/index";
	}

	@RequestMapping(value = { "/logout" })
	public String logout(Model model, HttpSession session,
			HttpServletRequest request, HttpServletResponse response) {
		try {
			User user1 = (User) session.getAttribute("user");
			setCookie(request, response, "user", user1.getId() + "", 0, true);
			setCookie(request, response, ADMIN, "" + isAdmin(session), 0, true);
			setLogOutStatus(session);
			MDC.put("userId", user1.getWorkerId());
			MDC.put("userType", isAdmin(session) ? 0 : 1);
			logger.info("用户工号" + user1.getWorkerId() + ",姓名"
					+ user1.getUserName() + "下线了");
		} catch (Exception e) {
		}
		return redirect("/login");
	}

	/**
	 * 产生验证码的方法
	 * */
	@RequestMapping(value = "/captcha-image", method = RequestMethod.GET)
	public void createCaptcha(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		response.setDateHeader("Expires", 0);
		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");
		// return a jpeg
		response.setContentType("image/jpeg");
		// create the text for the image
		String capText = captchaProducer.createText();
		// store the text in the session
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,
				capText);
		// create the image with the text
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = response.getOutputStream();
		// write the data out
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
	}

	@RequestMapping("/meeting")
	public String setMeetingMode(Model model, HttpSession session,
			HttpServletRequest request, HttpServletResponse response) {
		if (!isLogin(session)) {
			return redirect("/login");
		}
		setCookie(request, response, PREFERENCE, "meeting", MAXAGE, true);
		session.setAttribute(PREFERENCE, "meeting");
		return "/index/index";
	}

	@RequestMapping("/function")
	public String setFuctionMode(Model model, HttpSession session,
			HttpServletRequest request, HttpServletResponse response) {
		if (!isLogin(session)) {
			return redirect("/login");
		}
		setCookie(request, response, PREFERENCE, "function", MAXAGE, true);
		session.setAttribute(PREFERENCE, "function");
		return "/index/index";
	}

	@RequestMapping("/time")
	public String setTimeMode(Model model, HttpSession session,
			HttpServletRequest request, HttpServletResponse response) {
		if (!isLogin(session)) {
			return redirect("/login");
		}
		setCookie(request, response, PREFERENCE, "time", MAXAGE, true);
		session.setAttribute(PREFERENCE, "time");
		return "/index/index";
	}

	@RequestMapping("/other")
	public String setOtherMode(Model model, HttpSession session,
			HttpServletRequest request, HttpServletResponse response) {
		if (!isLogin(session)) {
			return redirect("/login");
		}
		setCookie(request, response, PREFERENCE, "other", MAXAGE, true);
		session.setAttribute(PREFERENCE, "other");
		return "/index/index";
	}

	@RequestMapping("/status")
	public String status(HttpSession session, Model model, String meetingId,
			String bookStartTime, String bookEndTime) {
		// List<MeetingModel> aMeetings = meetingBookService.getMeetingState(
		// "building='A'", "floor asc,number asc");
		// List<MeetingModel> bMeetings = meetingBookService.getMeetingState(
		// "building='B'", "floor asc,number asc");
		// model.addAttribute("meeting_rooms_a", aMeetings);
		// model.addAttribute("meeting_rooms_b", bMeetings);
		if (!isLogin(session)) {
			return redirect("/login");
		}
		List<Meeting> meetings = meetingsService
				.findByWhereAndOrder( " meetingRight<=" + getUserRight(session), null);
		model.addAttribute("meetingRooms", meetings);
		model.addAttribute("meetingId", meetingId);
		model.addAttribute("bookStartTime", bookStartTime);
		model.addAttribute("bookEndTime", bookEndTime);
		return "/status/status";
	}

	@RequestMapping("/room")
	public String room(HttpSession session, Model model) {
		// List<MeetingModel> aMeetings = meetingBookService.getMeetingState(
		// "building='A'", "floor asc,number asc");
		// List<MeetingModel> bMeetings = meetingBookService.getMeetingState(
		// "building='B'", "floor asc,number asc");
		// model.addAttribute("meeting_rooms_a", aMeetings);
		// model.addAttribute("meeting_rooms_b", bMeetings);
		if (!isLogin(session)) {
			return redirect("/login");
		}
		return "/room/room";
	}

	@ResponseBody
	@RequestMapping(value = "/meetings/all", method = RequestMethod.GET)
	public Object meetings(Model model) {
		List<Meeting> aMeetings = meetingsService.findByWhereAndOrder(
				"building='A'", "floor asc,number asc");
		List<Meeting> bMeetings = meetingsService.findByWhereAndOrder(
				"building='B'", "floor asc,number asc");
		model.addAttribute("meeting_rooms_a", aMeetings);
		model.addAttribute("meeting_rooms_b", bMeetings);
		return new Object[] { aMeetings, bMeetings };
	}

	/**
	 * ajax设置其选择模式
	 * */
	@RequestMapping(value = "/selectMode", method = RequestMethod.GET)
	@ResponseBody
	public boolean selectMode(Model model, String mode,
			HttpServletRequest request, HttpServletResponse response,
			HttpSession session) {
		if (!isLogin(session)) {
			return false;
		}
		setCookie(request, response, PREFERENCE, mode, MAXAGE, true);
		session.setAttribute(PREFERENCE, mode);
		return true;
	}

	/**
	 * ajax校验验证码是否正确
	 * */
	@RequestMapping(value = "/checkVerifyCode", method = RequestMethod.GET)
	@ResponseBody
	public boolean checkVerifyCode(Model model, String verifycode,
			HttpSession session) {
		String code = (String) session
				.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if (!code.equals(verifycode)) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * ajax校验工号是否正确
	 * */
	@RequestMapping(value = "/checkUserId", method = RequestMethod.GET)
	@ResponseBody
	public boolean checkUserId(Model model, String user, HttpSession session) {
		if (userService.findByWorkerId(user) == null) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * ajax校验密码是否正确
	 * */
	@RequestMapping(value = "/checkPwd", method = RequestMethod.GET)
	@ResponseBody
	public boolean checkUserId(Model model, String user, String pwd,
			HttpSession session) {
		User user1 = null;
		if ((user1 = userService.findByWorkerId(user)) == null) {
			return false;
		} else {
			if (user1.getPwd().equals(encrypt(pwd))) {
				return true;
			}
			return false;
		}
	}

	@RequestMapping(value = "/meetings/book", method = RequestMethod.GET)
	@ResponseBody
	public boolean book(String startdate, String enddate, String meetingId,
			String title, String details, HttpSession session) {
		try {
			Date startTime = parseDate(startdate);
			Date endTime = parseDate(enddate);
			if (!checkTime(startTime, endTime)) {
				return false;
			}
			boolean result = meetingBookService.bookMeetingRoom(
					getUserID(session), getWorkerID(session), startTime,
					endTime, Integer.parseInt(meetingId), title, details);
			if (result) {
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("预定会议" + title + "成功!");
			}
			return result;
		} catch (Exception e) {
			MDC.put("userId", getWorkerID(session));
			MDC.put("userType", isAdmin(session) ? 0 : 1);
			logger.info("预定会议失败!", e.getCause());
			return false;
		}

	}

	@RequestMapping(value = "/meetings/books")
	@ResponseBody
	public List<MeetingBook> getBooks(String start, String end,
			HttpSession session) {
		try {
			Date startTime = parseDate(start);
			Date endTime = parseDate(end);
			if (startTime.after(endTime)) {
				return null;
			}
			return meetingBookService.getBooks(startTime, endTime,
					CommonParamter.ALL_USER);

		} catch (Exception e) {
			return null;
		}

	}

	@RequestMapping(value = "/meetings/use")
	@ResponseBody
	public List<MeetingUse> getUses(String date, HttpSession session) {
		try {
			Date day = DateUtils.parseDate(date);
			return meetingUseService.getMeetingUses(getUserRight(session), day);

		} catch (Exception e) {
			return null;
		}

	}

	@RequestMapping(value = "/meetings/books/my")
	@ResponseBody
	public List<MeetingBook> getMyBooks(String start, String end,
			HttpSession session) {
		try {
			Date startTime = parseDate(start);
			Date endTime = parseDate(end);
			if (startTime.after(endTime)) {
				return null;
			}
			return meetingBookService.getBooks(startTime, endTime,
					getUserID(session));

		} catch (Exception e) {
			return null;
		}

	}

	@RequestMapping(value = " /meetings/filter")
	@ResponseBody
	public List<Meeting> getFilterMeetings(String sql) {
		return meetingsService.findByFilter(sql);
	}

	@RequestMapping(value = "/meetings/books/{meetingId}")
	@ResponseBody
	public List<MeetingBook> getBooks(String start, String end,
			@PathVariable String meetingId, HttpSession session) {
		try {
			Date startTime = parseDate(start);
			Date endTime = parseDate(end);
			int id = Integer.parseInt(meetingId);
			if (startTime.after(endTime)) {
				return null;
			}
			return meetingBookService.getBooks(startTime, endTime,
					CommonParamter.ALL_USER, id);

		} catch (Exception e) {
			return null;
		}

	}

	@RequestMapping(value = "/meetings/delete/{eventId}", method = RequestMethod.POST)
	@ResponseBody
	public boolean deleteEvent(@PathVariable String eventId, HttpSession session) {
		try {
			int id = Integer.parseInt(eventId);
			MeetingBook book = meetingBookService.find(id);
			boolean result = meetingBookService.deleteBook(getUserID(session),
					id);
			MDC.put("userId", getWorkerID(session));
			MDC.put("userType", isAdmin(session) ? 0 : 1);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("book", book);
			thirdVelocityEmailService.sendEmail(map, "您的会议预订已被删除",
					"com/fujitsu/cn/fnst/mailTemplates/deleteBook.vm",
					new String[] { getEmail(session) }, new String[] {});
			logger.info("删除会议" + eventId + "成功!");
			return result;
		} catch (Exception e) {
			MDC.put("userId", getWorkerID(session));
			MDC.put("userType", isAdmin(session) ? 0 : 1);
			logger.error("删除会议" + eventId + "失败!", e.getCause());
			return false;
		}

	}

	/***
	 * 
	 * 校验结束时间和开始时间
	 * */
	private boolean checkTime(Date startTime, Date endTime) {

		if (endTime.before(startTime)
				|| !startTime
						.after(DateUtils.getFormattedStartTime(new Date()))) {
			return false;
		}
		return true;
	}

	/**
	 * 
	 * 周期预订检查
	 * **/
	@RequestMapping(value = "/meetings/book/periodic", method = RequestMethod.GET)
	@ResponseBody
	public List<List<String>> bookLot(String startdate, String enddate,
			String meetingId, String title, String details,
			HttpSession session, String repweeks, String weeks) {
		try {
			Date startTime = parseDate(startdate);
			Date endTime = parseDate(enddate);
			int mettingIdInt = Integer.parseInt(meetingId);
			long left = endTime.getTime() - startTime.getTime();
			int weeksInt = Integer.parseInt(repweeks);
			if (weeks == null) {
				return null;
			}
			String[] weekday = weeks.split(",");
			List<Integer> weekdayInt = new ArrayList<Integer>();
			for (String day : weekday) {
				weekdayInt.add(Integer.parseInt(day));
			}
			if (!checkTime(startTime, endTime)) {
				return null;
			}
			List<Date> dates = new ArrayList<Date>();
			for (int i = 0; i <= weeksInt; i++) {
				List<Date> list = DateUtils.getWeekDate(startTime, i);
				for (int intValue : weekdayInt) {
					Date date = list.get(intValue);
					if (!date.before(startTime)) {
						dates.add(date);
					}
				}

			}
			List<List<String>> list = new ArrayList<List<String>>();
			List<String> success = new ArrayList<String>();
			List<String> failed = new ArrayList<String>();
			for (Date date : dates) {
				boolean result = meetingUseService.checkMeetingisVaild(date,
						new Date(date.getTime() + left), mettingIdInt);
				if (!result) {
					success.add(DateUtils.format(date));
				} else {
					failed.add(DateUtils.format(date));
				}
			}
			list.add(success);
			list.add(failed);
			return list;
		} catch (Exception e) {
			return null;
		}

	}

	/**
	 * 
	 * 周期预订
	 * **/
	@ResponseBody
	@RequestMapping(value = "/meetings/book/lot")
	public int bookLot1(String startdate, String enddate, String meetingId,
			String title, String details, HttpSession session, String repweeks,
			String weeks) {
		try {
			if (getUserRight(session) < UserRight.period.getRight()) {
				return -1;
			}
			Date startTime = parseDate(startdate);
			Date endTime = parseDate(enddate);
			int mettingIdInt = Integer.parseInt(meetingId);
			long left = endTime.getTime() - startTime.getTime();
			int weeksInt = Integer.parseInt(repweeks);
			if (weeks == null) {
				return -2;
			}
			String[] weekday = weeks.split(",");
			List<Integer> weekdayInt = new ArrayList<Integer>();
			for (String day : weekday) {
				weekdayInt.add(Integer.parseInt(day));
			}
			if (!checkTime(startTime, endTime)) {
				return -3;
			}
			List<Date> dates = new ArrayList<Date>();
			for (int i = 0; i <= weeksInt; i++) {
				List<Date> list = DateUtils.getWeekDate(startTime, i);
				for (int intValue : weekdayInt) {
					Date date = list.get(intValue);
					if (!date.before(startTime)) {
						dates.add(date);
					}
				}

			}
			for (Date date : dates) {
				meetingBookService.bookMeetingRoom(getUserID(session),
						getWorkerID(session), date, new Date(date.getTime()
								+ left), mettingIdInt, title, details);
			}
			MDC.put("userId", getWorkerID(session));
			MDC.put("userType", isAdmin(session) ? 0 : 1);
			// 这尼玛js写的我蛋疼啊
			logger.info("一大波预约会议" + startdate + "-" + enddate + " " + repweeks
					+ "  " + weeks + "成功!");
			return 0;
		} catch (Exception e) {
		}
		return -4;

	}

	@RequestMapping(value = { "/changepwd" }, method = RequestMethod.GET)
	public String changePwd(Model model, HttpSession session) {
		if (!isLogin(session)) {
			return redirect("/login");
		}
		return "changepwd/changepwd";
	}

	@RequestMapping(value = { "/changepwd" }, method = RequestMethod.POST)
	public String modifyPwd(Model model, HttpSession session, String pwd,
			String newpwd) {
		if (!isLogin(session)) {
			return redirect("/login");
		}
		User user = (User) session.getAttribute("user");
		if (pwd != null && encrypt(pwd).equals(user.getPwd())) {
			if (newpwd != null) {
				user.setPwd(encrypt(newpwd));
				user.setUpdateTime(new Date());
				// 乱码
				userService.modify(user);
				session.setAttribute("user", user);
				model.addAttribute("msg", "成功修改了密码！");
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("修改密码成功!");
			} else {
				model.addAttribute("msg", "密码修改失败！新密码为空");
			}
		} else {
			model.addAttribute("msg", "密码修改失败！请输入正确的密码！");
		}

		return "changepwd/changepwd";
	}

	@RequestMapping(value = { "/book/my" }, method = RequestMethod.GET)
	public String myBook(Model model, HttpSession session) {
		List<MeetingBook> books = meetingBookService.getBooks(new Date(),
				getUserID(session));
		model.addAttribute("myBooks", books);
		return "/my/my";
	}

	@RequestMapping(value = { "/books/modify/my/{bookeId}" }, method = RequestMethod.GET)
	public String modifyMyBook(HttpSession session,
			@PathVariable String bookeId, Model model)
			throws Resource404Exception {
		try {
			int id = Integer.parseInt(bookeId);
			MeetingBook book = meetingBookService.find(id);
			if (book == null) {
				throw new Resource404Exception("没有找到会议");
			}
			model.addAttribute("book", book);
			model.addAttribute("options", getParams());
		} catch (Exception e) {
			throw new Resource404Exception(e.getMessage());
		}
		return "/my/modify";
	}

	@RequestMapping(value = { "/books/modify/my/{bookeId}" }, method = RequestMethod.POST)
	public String modifyMyBook(HttpSession session, MeetingBook meetingBook,
			@PathVariable String bookeId, Model model)
			throws Resource404Exception {
		try {
			if (isLogin(session)
					&& getWorkerID(session)
							.equals(((User) session.getAttribute("user"))
									.getWorkerId())) {
				meetingBook.setUpdateTime(new Date());
				meetingBookService.modify(meetingBook);
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("修改会议成功!");
				model.addAttribute("result", "修改成功！");
			} else {
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("修改会议失败!");
				model.addAttribute("result", "修改失败！请重新登录！");
			}

			int id = Integer.parseInt(bookeId);
			meetingBook = meetingBookService.find(id);
			if (meetingBook == null) {
				throw new Resource404Exception("没有找到会议");
			}
			model.addAttribute("book", meetingBook);
			model.addAttribute("options", getParams());
		} catch (Exception e) {
			throw new Resource404Exception(e.getMessage());
		}
		return redirect("/book/my");
	}

	@RequestMapping(value = { "/book/his" }, method = RequestMethod.GET)
	public String myBookHis(Model model, HttpSession session) {
		List<MeetingBook> books = meetingBookService.getHisBooks(new Date(),
				getUserID(session));
		model.addAttribute("myHisBooks", books);
		return "/his/his";
	}

	@RequestMapping(value = { "/{type}/list" }, method = RequestMethod.GET)
	public String listAdmin(HttpSession session, @PathVariable String type,
			Model model) {
		if (type == null || !adminLinks.contains(type)) {
			type = adminLinks.get(0);
		}
		if (type.equals("tops")) {
			Date now = new Date();
			Date monthBeginDay = DateUtils.getMonthBeginDay(now);
			Date monthEndDay = DateUtils.getMonthEndDay(now);
			List<Map<Integer, Float>> map = meetingBookService
					.getTopFiveUsedMeetingRooms(monthBeginDay, monthEndDay);
			List<Map<Integer, Float>> map2 = meetingBookService
					.getTopFiveUsedPerson(monthBeginDay, monthEndDay);
			model.addAttribute("tops", map);
			model.addAttribute("topUsers", map2);
		}
		return "/admin/" + type + "/" + type;
	}

	@RequestMapping(value = { "/meetings/modify/{meetingId}" }, method = RequestMethod.GET)
	public String modifyMeeting(HttpSession session,
			@PathVariable String meetingId, Model model)
			throws Resource404Exception {
		try {
			int id = Integer.parseInt(meetingId);
			Meeting meeting = meetingsService.find(id);
			if (meeting == null) {
				throw new Resource404Exception("会议室未找到！");
			}
			model.addAttribute("meeting", meeting);
			model.addAttribute("options", getParams());
		} catch (Exception e) {
			throw new Resource404Exception(e.getMessage());
		}
		return "/admin/meetings/modify";
	}

	@RequestMapping(value = { "/meetings/modify/{meetingId}" }, method = RequestMethod.POST)
	public String modifyMeeting(HttpSession session, Meeting meeting,
			@PathVariable String meetingId, Model model)
			throws Resource404Exception {
		try {
			if (isAdmin(session)) {
				meeting.setUpdateTime(new Date());
				meetingsService.modify(meeting);
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("修改会议室" + meetingId + "成功!");
				model.addAttribute("result", "修改成功！");
			} else {
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("修改会议室" + meetingId + "失败!");
				model.addAttribute("result", "修改失败！请重新登录！");
			}
			int id = Integer.parseInt(meetingId);
			meeting = meetingsService.find(id);
			if (meeting == null) {
				throw new Resource404Exception("会议室未找到！");
			}
			model.addAttribute("meeting", meeting);
			model.addAttribute("options", getParams());
		} catch (Exception e) {
			throw new Resource404Exception(e.getMessage());
		}
		return "/admin/meetings/modify";
	}

	@RequestMapping(value = { "/meetings/delete/{meetingId}" }, method = RequestMethod.GET)
	public String deleteMeeting(HttpSession session,
			@PathVariable String meetingId, Model model)
			throws Resource404Exception {
		try {
			if (isAdmin(session)) {
				int id = Integer.parseInt(meetingId);
				Meeting meeting = meetingsService.find(id);
				if (meeting == null) {
					throw new Resource404Exception("会议室未找到！");
				}
				meetingsService.delete(meeting);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("meeting", meeting);
				thirdVelocityEmailService
						.sendEmail(
								map,
								"一个会议室被删除了",
								"com/fujitsu/cn/fnst/mailTemplates/deleteMeetingRoom.vm",
								getEmails(), new String[] {});
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("删除会议室" + meetingId + "成功!");
				model.addAttribute("result", "删除成功！");
			}
		} catch (Exception e) {
			throw new Resource404Exception(e.getMessage());
		}

		return redirect("/meetings/list");
	}

	@RequestMapping(value = { "/meetings/add" }, method = RequestMethod.GET)
	public String addMeeting(HttpSession session, Model model) {
		model.addAttribute("options", getParams());
		return "/admin/meetings/add";
	}

	@RequestMapping(value = { "/meetings/add" }, method = RequestMethod.POST)
	public String addMeeting(HttpSession session, Meeting meeting, Model model) {
		if (isAdmin(session)) {
			Date now = new Date();
			meeting.setCreateTime(now);
			meeting.setUpdateTime(now);
			meetingsService.add(meeting);
			MDC.put("userId", getWorkerID(session));
			MDC.put("userType", isAdmin(session) ? 0 : 1);
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("meeting", meeting);
			thirdVelocityEmailService.sendEmail(map, "一个新的会议室可以使用了",
					"com/fujitsu/cn/fnst/mailTemplates/addMeetingRoom.vm",
					getEmails(), new String[] {});
			logger.info("添加会议室" + meeting.getId() + "--"
					+ meeting.getMeetingName() + "成功!");
		}
		return redirect("/meetings/list");
	}

	@RequestMapping(value = { "/users/modify/{userId}" }, method = RequestMethod.GET)
	public String modifyUser(HttpSession session, @PathVariable String userId,
			Model model) throws Resource404Exception {
		try {
			int id = Integer.parseInt(userId);
			User user = userService.find(id);
			if (user == null) {
				throw new Resource404Exception("没有找到该用户!");
			}
			model.addAttribute("userModel", user);
			model.addAttribute("options", getParams());
		} catch (Exception e) {
			throw new Resource404Exception(e.getMessage());
		}
		return "/admin/users/modify";
	}

	@RequestMapping(value = { "/users/modify/{userId}" }, method = RequestMethod.POST)
	public String modifyUser(HttpSession session, User userModel,
			@PathVariable String userId, Model model)
			throws Resource404Exception {
		try {
			if (isAdmin(session)) {
				userModel.setUpdateTime(new Date());
				userModel.setPwd(encrypt(userModel.getPwd()));
				userService.modify(userModel);
				MDC.put("userId", userModel.getWorkerId());
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("修改用户成功!");
				model.addAttribute("result", "修改成功！");
			} else {
				MDC.put("userId", userModel.getWorkerId());
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("修改用户失败!");
				model.addAttribute("result", "修改失败！请重新登录！");
			}

			int id = Integer.parseInt(userId);
			userModel = userService.find(id);
			if (userModel == null) {
				throw new Resource404Exception("没有找到该用户");
			}
			model.addAttribute("userModel", userModel);
			model.addAttribute("options", getParams());
		} catch (Exception e) {
			throw new Resource404Exception(e.getMessage());
		}
		return "/admin/users/modify";
	}

	@RequestMapping(value = { "/users/delete/{userId}" }, method = RequestMethod.GET)
	public String deleteUser(HttpSession session, @PathVariable String userId,
			Model model) throws Resource404Exception {
		try {
			if (isAdmin(session)) {
				int id = Integer.parseInt(userId);
				User user = userService.find(id);
				if (user == null) {
					throw new Resource404Exception("没有找到该用户");
				}
				userService.delete(user);
				model.addAttribute("result", "删除成功！");
				MDC.put("userId", user.getWorkerId());
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("删除用户成功!");
			} else {
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("删除用户失败!");
			}
		} catch (Exception e) {
			throw new Resource404Exception(e.getMessage());
		}

		return redirect("/users/list");
	}

	@RequestMapping(value = { "/users/add" }, method = RequestMethod.GET)
	public String addUser(HttpSession session, Model model) {
		model.addAttribute("options", getParams());
		return "/admin/users/add";
	}

	@RequestMapping(value = { "/users/add" }, method = RequestMethod.POST)
	public String addUser(HttpSession session, User userModel, Model model) {
		if (isAdmin(session)) {
			userModel.setPwd(encrypt(userModel.getPwd()));
			Date now = new Date();
			userModel.setCreateTime(now);
			userModel.setUpdateTime(now);
			userService.add(userModel);
			MDC.put("userId", userModel.getWorkerId());
			MDC.put("userType", isAdmin(session) ? 0 : 1);
			logger.info("添加用户成功!");
		}
		return redirect("/users/list");
	}

	@RequestMapping(value = { "/books/modify/{bookeId}" }, method = RequestMethod.GET)
	public String modifyBook(HttpSession session, @PathVariable String bookeId,
			Model model) throws Resource404Exception {
		try {
			int id = Integer.parseInt(bookeId);
			MeetingBook book = meetingBookService.find(id);
			if (book == null) {
				throw new Resource404Exception("没有找到会议");
			}
			model.addAttribute("book", book);
			model.addAttribute("options", getParams());
		} catch (Exception e) {
			throw new Resource404Exception(e.getMessage());
		}
		return "/admin/books/modify";
	}

	@RequestMapping(value = { "/books/modify/{bookeId}" }, method = RequestMethod.POST)
	public String modifyBook(HttpSession session, MeetingBook meetingBook,
			@PathVariable String bookeId, Model model)
			throws Resource404Exception {
		try {
			if (isAdmin(session)) {
				meetingBook.setUpdateTime(new Date());
				meetingBookService.modify(meetingBook);
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("修改会议成功!");
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("book", meetingBook);
				thirdVelocityEmailService.sendEmail(map, "您的会议预订已被修改",
						"com/fujitsu/cn/fnst/mailTemplates/modifyBook.vm",
						new String[] { getEmail(session) }, new String[] {});
				model.addAttribute("result", "修改成功！");
			} else {
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("修改会议失败!");
				model.addAttribute("result", "修改失败！请重新登录！");
			}

			int id = Integer.parseInt(bookeId);
			meetingBook = meetingBookService.find(id);
			if (meetingBook == null) {
				throw new Resource404Exception("没有找到会议");
			}
			model.addAttribute("book", meetingBook);
			model.addAttribute("options", getParams());
		} catch (Exception e) {
			throw new Resource404Exception(e.getMessage());
		}
		return "/admin/books/modify";
	}

	@ResponseBody
	@RequestMapping(value = { "/books/delete/my/{bookId}" }, method = RequestMethod.GET)
	public boolean deleteMyBook(HttpSession session,
			@PathVariable String bookId, Model model) {
		try {
			if (isLogin(session)) {
				int id = Integer.parseInt(bookId);
				MeetingBook meetingBook = meetingBookService.find(id);
				if (meetingBook == null) {
					return false;
				}
				if (meetingBook.getWorkerId().equals(getWorkerID(session))) {
					meetingBookService.delete(meetingBook);
					MDC.put("userId", getWorkerID(session));
					MDC.put("userType", isAdmin(session) ? 0 : 1);
					Map<String, Object> map = new HashMap<String, Object>();
					map.put("book", meetingBook);
					thirdVelocityEmailService
							.sendEmail(
									map,
									"您的会议预订已被删除",
									"com/fujitsu/cn/fnst/mailTemplates/deleteBook.vm",
									new String[] { getEmail(session) },
									new String[] {});
					logger.info("删除会议成功!");
				} else {
					return false;
				}
			} else {
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("删除会议失败!");
				return false;
			}
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	@RequestMapping(value = { "/books/delete/{bookId}" }, method = RequestMethod.GET)
	public String deleteBook(HttpSession session, @PathVariable String bookId,
			Model model) throws Resource404Exception {
		try {
			if (isAdmin(session)) {
				int id = Integer.parseInt(bookId);
				MeetingBook meetingBook = meetingBookService.find(id);
				if (meetingBook == null) {
					throw new Resource404Exception("没有找到会议");
				}
				meetingBookService.delete(meetingBook);
				model.addAttribute("result", "删除成功！");
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("book", meetingBook);
				thirdVelocityEmailService.sendEmail(map, "您的会议预订已被删除",
						"com/fujitsu/cn/fnst/mailTemplates/deleteBook.vm",
						new String[] { getEmail(session) }, new String[] {});
				logger.info("删除会议成功!");
			} else {
				MDC.put("userId", getWorkerID(session));
				MDC.put("userType", isAdmin(session) ? 0 : 1);
				logger.info("删除会议失败!");
			}
		} catch (Exception e) {
			throw new Resource404Exception(e.getMessage());
		}
		return redirect("/books/list");
	}

	@RequestMapping(value = { "/books/add" }, method = RequestMethod.GET)
	public String addBook(HttpSession session, Model model) {
		model.addAttribute("options", getParams());
		return "/admin/books/add";
	}

	@RequestMapping(value = { "/books/add" }, method = RequestMethod.POST)
	public String addBook(HttpSession session, MeetingBook book, Model model) {
		if (isAdmin(session)) {
			Date now = new Date();
			book.setCreateTime(now);
			book.setUpdateTime(now);
			book.setUserId(getUserID(session));
			book.setWorkerId(getWorkerID(session));
			meetingBookService.add(book);
			MDC.put("userId", getWorkerID(session));
			MDC.put("userType", isAdmin(session) ? 0 : 1);
			logger.info("添加会议成功!");
		}
		return redirect("/books/list");
	}

	@RequestMapping(value = { "/switch2admin" })
	public String switch2Admin(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) {
		if (((User) session.getAttribute("user")).getIsAdmin() == CommonParamter.IS_ADMIN) {
			setCookie(request, response, ADMIN, "true", true);
			session.setAttribute(ADMIN, "true");
			setLogOutStatus(session);

		}
		return redirect("/index");
	}

	@RequestMapping(value = "/meetings/use/ajax")
	@ResponseBody
	public MeetingBook ajaxUse(String meetingId, String date, String clock) {
		try {
			int id = Integer.parseInt(meetingId);
			Date time = DateUtils.parseDate(date);
			float clockf = Float.parseFloat(clock);
			MeetingBook book = meetingBookService.getMeetingBook(id, time,
					clockf);
			return book;
		} catch (Exception e) {
		}
		return null;
	}

	@RequestMapping(value = { "/switch2normal" })
	public String switch2Normal(HttpSession session,
			HttpServletRequest request, HttpServletResponse response) {
		setCookie(request, response, ADMIN, "false", true);
		session.setAttribute(ADMIN, "false");
		setLogOutStatus(session);
		return redirect("/index");
	}

	@ResponseBody
	@RequestMapping("/books/excuted/my/{bookeId}")
	public boolean excutedBook(HttpSession session, @PathVariable String bookeId) {
		try {
			int id = Integer.parseInt(bookeId);
			MeetingBook book = meetingBookService.find(id);
			if (book == null) {
				return false;
			}
			if (book.getState() == BookState.excuting.getState()) {
				book.setState(BookState.excuted.getState());
				meetingBookService.modify(book);
				return true;
			}
		} catch (Exception e) {
		}
		return false;
	}

	@ResponseBody
	@RequestMapping("/books/excute/my/{bookeId}")
	public boolean excuteBook(HttpSession session, @PathVariable String bookeId) {
		try {
			int id = Integer.parseInt(bookeId);
			MeetingBook book = meetingBookService.find(id);
			if (book == null) {
				return false;
			}
			Date now = new Date();
			int timespan = Math
					.abs((int) ((book.getBookStartTime().getTime() - now
							.getTime()) / 1000 / 60));
			if (timespan <= 15) {
				book.setState(BookState.excuting.getState());
				meetingBookService.modify(book);
				return true;
			}
		} catch (Exception e) {
		}
		return false;
	}

	private List<Param> getParams() {
		List<Param> params = new ArrayList<Param>(2);
		Param param = new Param();
		param.setText("是");
		param.setValue("1");
		params.add(param);
		param = new Param();
		param.setText("否");
		param.setValue("0");
		params.add(param);
		return params;

	}

	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		binder.registerCustomEditor(Date.class, new DateConvertor());
	}

}
